//
//  MySQLConnect.swift
//  COpenSSL
//
//  Created by 陈志勇 on 2018/11/10.
//

import PerfectMySQL
import PerfectLogger

class MySQLConnect {
    /// 数据库IP
    var host: String {
        get {
            return "127.0.0.1"
        }
    }
    
    /// 数据库端口
    var prot: String {
        get {
            return "3306"
        }
    }
    
    /// 数据库用户名
    var user: String {
        get {
            return "root"
        }
    }
    
    /// 数据库密码
    var password: String {
        get {
            return "123456"
        }
    }
    
    /// 用于操作mysql的句柄
    private var mysql: MySQL!
    /// mysql句柄单例
    private static var instance: MySQL!
    static func shareInstance(dataBaseName: String) -> MySQL {
        if instance == nil {
            instance = MySQLConnect(dataBaseName: dataBaseName).mysql
        }
        return instance
    }
    
    /// 私有构造器
    private init(dataBaseName: String) {
        self.conncetDataBase()
        self.selectDataBase(name: dataBaseName)
    }
    
    /// 连接数据库
    private func conncetDataBase() {
        if mysql == nil {
            mysql = MySQL()
        }
        let connected = mysql.connect(host: host, user: user, password: password)
        guard connected else {
            LogFile.error(mysql.errorMessage())
            return
        }
        LogFile.info("数据库连接成功")
    }
    
    /// 选择数据库
    private func selectDataBase(name: String) {
        guard mysql.selectDatabase(named: name) else {
            LogFile.error("数据库连接失败。错误代码：\(mysql.errorCode()) 错误解释：\(mysql.errorMessage())")
            return
        }
        LogFile.info("连接Schema: \(name)成功")
    }
}

let ResultKey = "result"
let ResultListKey = "list"
let ErrorMessageKey = "errorMessage"
let RequestResultSuccess = "SUCCESS"
let RequestResultFaile = "FAILE"
var BaseResponseJson: [String : Any] = [ResultListKey: [],
                                        ResultKey: RequestResultSuccess,
                                        ErrorMessageKey: ""]

class BaseOperator {
    let dataBaseName = "test"
    var mysql: MySQL {
        get {
            return MySQLConnect.shareInstance(dataBaseName: dataBaseName)
        }
    }
    var responseJson = BaseResponseJson
}
